package com.spark.colliery.widget

import android.annotation.SuppressLint
import android.content.Context
import android.text.SpannableString
import android.text.Spanned
import android.text.style.RelativeSizeSpan
import android.text.style.SuperscriptSpan
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.widget.TextView
import com.spark.colliery.R

/**
 * Created by shuttle on 2018/1/17.
 */

@SuppressLint("AppCompatCustomView")
class NotifyTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = -1) : TextView(context, attrs, defStyleAttr) {

    init {
        init()
    }

    private fun init() {
        background = resources.getDrawable(R.drawable.icon_notify_msg_bg)
        setPadding(dp2px(2f).toInt(), dp2px(2f).toInt(), dp2px(2f).toInt(), dp2px(2f).toInt())
        setTextColor(resources.getColor(R.color.spark_white))
        setTextSize(TypedValue.COMPLEX_UNIT_SP, 9f)
        visibility = View.GONE
    }

    fun setNum(num: Int) {
        if (num <= 0) {
            visibility = View.GONE
        } else {
            visibility = View.VISIBLE
            if (num < 99) {
                text = num.toString()
            } else {
                val spannableString = SpannableString("99+")
                val superscriptSpan = SuperscriptSpan()
                val sizeSpan = RelativeSizeSpan(0.7f)
                spannableString.setSpan(superscriptSpan, 2, 3, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
                spannableString.setSpan(sizeSpan, 2, 3, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
                text = spannableString
            }
        }
    }


    /**
     * dp2px
     *
     * @param dp target dp
     * @return the unit of result is px
     */
    private fun dp2px(dp: Float): Float {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.displayMetrics)
    }
}
